<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use Carbon\Carbon;

class LoginController extends Controller
{
    public function login(Request $request)
    {
        try {
            $request->validate([
                'username' => 'required|string',
                'password' => 'required|string',
            ]);

            // 检查是否是管理员用户登录
            if ($request->username === 'admin' && $request->password === 'admin') {
                // 检查管理员用户是否存在
                $user = User::where('username', 'admin')
                            ->where('is_deleted', false)
                            ->where('status', 1)
                            ->first();

                // 如果不存在，创建管理员用户
                if (!$user) {
                    $user = User::create([
                        'username' => 'admin',
                        'password' => Hash::make('admin'),
                        'status' => 1,
                        'create_time' => Carbon::now(),
                        'update_time' => Carbon::now(),
                        'is_deleted' => false
                    ]);
                }

                // 生成简单的 token
                $token = md5(uniqid($user->id, true));

                return response()->json([
                    'code' => 200,
                    'message' => '登录成功',
                    'data' => [
                        'token' => $token,
                        'user' => [
                            'id' => $user->id,
                            'username' => $user->username,
                            'status' => $user->status,
                            'create_time' => $user->create_time,
                            'update_time' => $user->update_time,
                            'is_deleted' => $user->is_deleted
                        ]
                    ]
                ]);
            }

            return response()->json([
                'code' => 401,
                'message' => '用户名或密码错误'
            ], 401);

        } catch (\Exception $e) {
            return response()->json([
                'code' => 500,
                'message' => '登录失败',
                'error' => $e->getMessage()
            ], 500);
        }
    }
} 